<template>
    <div class="region-distribution">
<!--        <el-button-group class="region-distribution__index-btn-group">-->
<!--            <el-button class="label">指标</el-button>-->
<!--            <el-select v-model="value" placeholder="请选择">-->
<!--                <el-option-->
<!--                        v-for="item in options"-->
<!--                        :key="item.value"-->
<!--                        :label="item.label"-->
<!--                        :value="item.value">-->
<!--                </el-option>-->
<!--            </el-select>-->
<!--        </el-button-group>-->
        <el-row type="flex" justify="space-between" class="region-distribution__main-content">
            <el-col class="map-wrap main-content_item" :span="12" v-loading="loadingMap">
                <el-row class="checkbox-wrap" type="flex">
                    <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选
                    </el-checkbox>
                    <el-checkbox-group v-model="checkedType" @change="handleCheckedTypesChange">
                        <el-checkbox v-for="{label, value} in typeOptions" :label="value" :key="label">{{label}}</el-checkbox>
                    </el-checkbox-group>
                </el-row>
                <div v-auto-resize class="chart-wrap map" ref="chartEl" style="height: 100%"/>
            </el-col>
            <el-col class="table-wrap main-content_item" :span="12" v-loading="loadingTable">
                <TableSimple height="28vh" :tableData="tableData"/>
            </el-col>
        </el-row>
    </div>
</template>

<script>
import throttle from 'lodash/throttle'
import axios from 'axios'
import echarts from 'echarts'
import EchartsBase from '@/mixins/echarts-base'
import AutoResize from '@/directive/echart-resizer'
import { subComponentMixin } from '@/mixins/user-data'
import TableSimple from './table-simple'

let oChart
let geoJson, GeoCoordMap, distributeArr
export default {
  name: 'RegionDistribution',
  mixins: [EchartsBase, subComponentMixin],
  directives: {
    AutoResize
  },
  components: {
    TableSimple
  },
  data () {
    return {
      loadingMap: true,
      loadingTable: true,
      options: [{
        value: '1',
        label: '浏览量（pv）'
      }],
      value: '1',
      checkAll: false,
      checkedType: [],
      typeOptions: [
        {
          label: '新安装设备',
          value: 'registDeviceCount'
        },
        {
          label: '新增用户',
          value: 'newAppUserCount'
        },
        {
          label: '活跃用户',
          value: 'activeUserCount'
        },
        {
          label: '沉默用户',
          value: 'silentUserCount'
        },
        {
          label: '流失用户',
          value: 'lostUserCount'
        }],
      isIndeterminate: true,
      tableData: {
        column: [
          {
            label: '省份',
            prop: 'provinceName'
          },
          {
            label: '浏览量（PV）',
            prop: 'pv'
          },
          {
            label: '占比',
            prop: 'percent'
          }
        ],
        data: []
      },
      throttleSetOption: throttle(this.setOption, 300)
    }
  },
  created () {
    this.handleCheckAllChange(true)
    Promise.all([axios.get('./geo-json/100000.json'),
      this._getUserAreaInfo()])
      .then(([{ data: geoData }]) => {
        geoJson = geoData
        echarts.registerMap('CHINA', geoJson)
        this.$nextTick().then(() => {
          oChart = echarts.init(this.$refs.chartEl)
          this.setOption()
        })
      })
    this._getUserAreaInfoTable()
  },
  methods: {
    getData () {
      this._getUserAreaInfo()
      this._getUserAreaInfoTable()
    },
    async _getUserAreaInfo () {
      this.loadingMap = true
      const { data: { data, code } } = await this.$http
        .get(this.getApiUrl('/dataanalysis_iot/user/getUserAreaInfo', false),
          {
            params: this.requestParams
          })
      this.loadingMap = false
      if (code === 0) {
        distributeArr = data
        if (oChart) {
          this.setOption()
        }
        return data
      }
    },
    async _getUserAreaInfoTable () {
      this.loadingTable = true
      const { data: { data, code } } = await this.$http
        .get(this.getApiUrl('/dataanalysis_iot/user/getUserAreaInfoTable', false),
          {
            params: this.requestParams
          })
      this.loadingTable = false
      if (code === 0) {
        this.tableData.data = data
        return data
      }
    },
    setOption () {
      this.loadingMap = true
      const geoCoordMap = this.constructGeoCoordMap()

      const convertData = (data) => {
        const res = []
        for (const item of data) {
          const { provinceName } = item
          let sum = 0
          let geoCoord = []
          for (const key of this.checkedType) {
            sum += (item[key] || 0)
          }
          if (geoCoordMap.has(provinceName)) {
            geoCoord = geoCoordMap.get(provinceName)
          } else {
            for (const key of geoCoordMap.keys()) {
              if (provinceName.indexOf(key) >= 0) {
                geoCoord = geoCoordMap.get(key)
                geoCoordMap.delete(key)
                geoCoordMap.set(provinceName, geoCoord)
                break
              }
            }
          }
          sum && res.push(geoCoord.concat(...[sum, provinceName]))
        }
        // console.log(res)
        return res
      }
      const scatterData = convertData(distributeArr)
      const option = {
        tooltip: {
          trigger: 'item'
        },
        visualMap: {
          type: 'continuous',
          min: 0,
          max: scatterData.reduce((result, [lon, lat, count]) => count > result ? count : result, 0),
          right: '1%',
          dimension: 2,
          orient: 'horizontal',
          text: ['高', '低'],
          color: ['#d94e5d', '#eac736', '#50a3ba'],
          textStyle: {
            color: '#000'
          }
        },
        geo: {
          map: 'CHINA',
          top: '2%',
          bottom: '2%',
          label: {
            emphasis: {
              show: false
            }
          },
          itemStyle: {
            normal: {
              areaColor: '#323c48',
              borderColor: '#111'
            },
            emphasis: {
              areaColor: '#2a333d'
            }
          },
          roam: true
        },
        series: [
          {
            name: 'data',
            type: 'scatter',
            coordinateSystem: 'geo',
            symbolSize: 12,
            label: {
              normal: {
                show: false
              },
              emphasis: {
                show: false
              }
            },
            itemStyle: {
              emphasis: {
                borderColor: '#fff',
                borderWidth: 1
              }
            },
            data: scatterData,
            tooltip: {
              formatter: ({ value: [x, y, val, pro] }) => `${pro}：${val}`
            }
          }
        ]
      }
      oChart.setOption(option)
      setTimeout(() => {
        this.loadingMap = false
      }, 300)
    },
    constructGeoCoordMap () {
      if (GeoCoordMap) {
        return GeoCoordMap
      }
      const geoArr = []
      const { features } = geoJson
      for (let i = 0; i < features.length; i++) {
        const { properties: { cp, name } } = features[i]
        geoArr.push([name, cp])
      }
      GeoCoordMap = new Map(geoArr)
      return GeoCoordMap
    },
    handleCheckAllChange (val) {
      this.checkedType = val ? this.typeOptions.map(({ value }) => value) : []
      this.isIndeterminate = false
      oChart && this.throttleSetOption()
    },
    handleCheckedTypesChange (value) {
      let checkedCount = value.length
      this.checkAll = checkedCount === this.typeOptions.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.typeOptions.length
      oChart && this.throttleSetOption()
    }
  }
}
</script>

<style lang="scss" scoped>
    @import "~element-theme-chalk/src/common/var.scss";
    @import "@/assets/scss/modules/variables-module.scss";

    .region-distribution {
        display: flex;
        flex-direction: column;

        .region-distribution__main-content {
            padding-top: $gap-default;

            .map-wrap {
                display: flex;
                flex-flow: column;

                .checkbox-wrap {
                    .el-checkbox-group {
                        margin-left: 30px;
                    }

                    ::v-deep {
                        .el-checkbox__input {
                            display: none;
                        }

                        .el-checkbox__label {
                            padding: 2px 10px;
                            border-radius: $--border-radius-base;
                            margin-bottom: 5px;
                        }

                        .el-checkbox.is-checked {
                            .el-checkbox__label {
                                color: $input-font-color;
                                background-color: $input-background-color;
                            }
                        }
                    }
                }
                .chart-wrap {
                    flex: auto;
                }
            }

            .table-wrap {
                .el-table {
                    ::v-deep {
                        .el-table__body-wrapper {
                            height: 100%;
                            overflow: auto;
                        }
                        .el-table__row {
                            font-weight: bold;
                        }
                    }
                }
            }
        }
    }

    .region-distribution__index-btn-group {
        ::v-deep {
            .label, .el-select .el-input__inner {
                color: $input-font-color;
                background-color: $input-background-color;
            }

            .el-select {
                .el-select__caret {
                    color: $select-caret-color;
                }
            }
        }
    }

</style>
